package org.ww.jd.auction;

import static org.ww.jd.utils.HttpClientUtils.doGetJson;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.ww.jd.JDURLConsts;
import org.ww.jd.log.Logger;
import org.ww.jd.utils.HttpClientUtils;

public class UnSessionUtils {
	private static CloseableHttpClient httpclient = HttpClients.createDefault();

	// public static void main(String[] args) throws Exception {
	// System.out.println(searchAuctionAll().size());
	// }

	public static List<GoodsInfo> searchAuctionAll(boolean onlyId) {
		long t = new Date().getTime() % 100;
		List<GoodsInfo> goodsList = new ArrayList<GoodsInfo>();
		String searchLocaltion = "/listing/0-0-0-0-111-1-0-1-1-" + t + ".html";

		int pageNo = 1;
		try {
			Document doc = HttpClientUtils.doGetHtml(httpclient,
					JDURLConsts.AUCTION_URL + searchLocaltion);

			Elements pageInfos = doc.getElementsByAttributeValue("class",
					"p-num");
			if (!pageInfos.isEmpty()) {
				Elements pages = pageInfos.get(0).getElementsByTag("a");
				int size = pages.size();
				Element el = pages.get(size - 2);
				pageNo = Integer.valueOf(el.ownText());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (int i = 0; i < pageNo; i++) {
			try {
				goodsList.addAll(searchAuctionAll(i + 1, onlyId));
			} catch (Exception e) {
				Logger.debug("error on page[" + (i + 1) + "]," + e.getMessage());
				Logger.error(e);
			}
		}
		return goodsList;
	}

	private static List<GoodsInfo> searchAuctionAll(int pageNo, boolean onlyId) {
		long t = new Date().getTime() % 100;
		List<GoodsInfo> goodsList = new ArrayList<GoodsInfo>();
		String searchLocaltion = "/listing/0-0-0-0-111-1-0-" + pageNo + "-1-"
				+ t + ".html";
		Document doc = HttpClientUtils.doGetHtml(httpclient,
				JDURLConsts.AUCTION_URL + searchLocaltion);
		// System.out.println(doc);
		Element paimailist = doc.getElementById("paimai_items");
		if (paimailist == null) {
			return goodsList;
		}
		Elements goodsInfos = paimailist.getElementsByTag("li");
		for (Element goodsInfo : goodsInfos) {
			// System.out.println(goodsInfo);
			// String name = goodsInfo.attr("title");
			String id = goodsInfo.attr("k");
			if (id == null || id.trim().length() == 0) {
				continue;
			}
			GoodsInfo goodsInfoVO;
			if (onlyId) {
				goodsInfoVO = new GoodsInfo(id);
			} else {
				goodsInfoVO = getGoods(id);
			}
			goodsList.add(goodsInfoVO);
		}
		return goodsList;
	}

	public static String doPriceWithBrowser(GoodsInfo goods, int newPrice) {
		String url = "http://auction.jd.com/json/paimai/bid?dealId="
				+ goods.getGoodsId() + "&price=" + newPrice;
		try {

			Desktop.getDesktop().browse(new URI(url));
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return url;
	}

	public static Long getServerTime() {
		try {
			long time = Calendar.getInstance().getTime().getTime();
			JSONObject json = doGetJson(httpclient,
					"http://auction.jd.com/json/paimai/now?t=" + time);
			return Long.valueOf(json.getLong("now"));
		} catch (Exception e) {
			return new Date().getTime();
		}
	}

	public static Double getCurrentPrice(String goodsid) {
		long time = Calendar.getInstance().getTime().getTime();
		JSONObject json = doGetJson(httpclient,
				"http://auction.jd.com/json/paimai/bid_records?t=" + time
						+ "&dealId=" + goodsid);
		try {
			json.has("auctionStatus");

			JSONArray array = json.getJSONArray("datas");
			if (array.length() == 0) {
				return Double.valueOf(1.0D);
			}
			JSONObject currentObj = (JSONObject) array.get(0);
			return Double.valueOf(currentObj.getDouble("price"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return Double.valueOf(1.0D);
	}

	public static GoodsInfo getGoods(String goodsid) {
		Document doc = HttpClientUtils.doGetHtml(httpclient,
				"http://auction.jd.com/detail/" + goodsid);
		Elements elements = doc.getElementsByAttributeValue("class", "p-info");
		if (elements.size() == 0) {
			return null;
		}
		GoodsInfo goodsInfo = HtmlUtils.convertGoodsInfo(goodsid,
				elements.get(0));
		Elements scriptElements = doc.getElementsByTag("script");
		Element dealModelEle = null;
		for (Element e : scriptElements) {
			if (e.toString().contains("var dealModel")) {
				dealModelEle = e;
				break;
			}
		}
		if (dealModelEle == null) {
			throw new RuntimeException("not found var dealModel");
		}
		String scripts = dealModelEle.toString();
		int start = scripts.indexOf("dealModel=");
		int end = scripts.indexOf("};", start + 1);
		String starttime = scripts.substring(start, end + 1).replaceAll(
				"dealModel=", "");
		try {
			JSONObject dealModel = new JSONObject(starttime);
			goodsInfo.setStartTimeMili(Long.valueOf(dealModel
					.getLong("startTimeMili")));
			goodsInfo.setEndTimeMili(Long.valueOf(dealModel
					.getLong("endTimeMili")));
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
		return goodsInfo;
	}

	// public static JSONArray doGetJsonArray(String url) {
	// JSONArray jsobj;
	// try {
	// jsobj = new JSONArray(doGetString(url));
	// } catch (JSONException e) {
	//
	// throw new RuntimeException(e);
	// }
	// return jsobj;
	// }

	public static void closeHttp() {
		try {
			if (httpclient != null)
				httpclient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
